package com.daz.student.homeWork.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.daz.common.Util.CommonUtil;
import com.daz.student.homeWork.pojo.HomeWorkFilePojo;
import com.daz.student.homeWork.server.IHomeWorkFileSV;
import com.github.pagehelper.PageInfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class HomeWorkFileFileAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private IHomeWorkFileSV sv;
	
	private String fileIds;
	private String fileID;
    private Boolean success;
    private String msg;
    private PageInfo<HomeWorkFilePojo> resultList;
    public String page;
	public String limit;
	public String query;
	private File upload; 
    private String uploadFileName;
  //  private InputStream downloadFile;
    public String downLoad(){
    	//downloadFile = getDownloadFile();
		return SUCCESS;
	}
    
    public InputStream getDownloadFile(){
		System.out.println("下载");
		InputStream in = null;
		Map<String, Object> searchconditionMap = new HashMap<String, Object>();
		searchconditionMap.put("fileId", fileID);
		try {
			//fileList = uploadFileServer.searchFile(searchconditionMap, 0, 0);
			resultList = sv.getFileList(searchconditionMap, 0, 0);
			uploadFileName=(String)resultList.getList().get(0).getFileName();
			uploadFileName=new String(uploadFileName.getBytes(), "ISO8859-1");
			this.setUploadFileName(uploadFileName);
			String filePath = (String)resultList.getList().get(0).getFilePath();
			File fieFile = new File(filePath);
			if(fieFile.exists()){
				in = new FileInputStream(fieFile);				
			}
			//uploadFileServer.updateFile(fileList.getList().get(0));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return in;
	}
    public String queryFileList(){
    	Map<String,Object> map = new HashMap<String, Object>();
    	Map<String, Object> session = ActionContext.getContext().getSession();
    	int s=0;
		int l=0;
		if(page!=null){
			s = Integer.parseInt(page);
		}
		if(limit != null){
			l = Integer.parseInt(limit);
		}
		String id="";
		if(ActionContext.getContext().getSession().get("teacherId") != null){
			if(CommonUtil.isNotBlank(ActionContext.getContext().getSession().get("teacherId").toString())){
				id = ActionContext.getContext().getSession().get("teacherId").toString();
			}
		
		}
		map.put("teacherId", id);
		if(query != null){
			map.put("query", query);
		}
    	try {
			resultList = sv.getFileList(map, s, l);
			this.setSuccess(true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return SUCCESS;
    }
    public String insert(){
    	Map<String, Object> session = ActionContext.getContext().getSession();
    	HomeWorkFilePojo value = new HomeWorkFilePojo();
    	try{
    	value.setStudentId(session.get("studentId").toString());
    	value.setTeacherId(session.get("teacherId").toString());
    	}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.setSuccess(false);
		}
    	Date date = new Date();
    	value.setUploadTime(date);
    	value.setFileName(uploadFileName);
    	SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
		 String str = sdf.format(date);
		 str = str.replace("_", "");str = str.replace(":", "");
		 //文件路劲名称:学号+时间+5位随机数+“_”+原文件名称
		 Long num  = (long) (Math.random() * 100000L);
		File pathFile = new File("E:\\homeWorkFile\\");
 		if(!pathFile.isDirectory()){
 			pathFile.mkdir();
 		}
    	String path = "E:\\homeWorkFile\\" +session.get("teacherId").toString()+"\\";
    	uploadFileName = session.get("studentId").toString() + str + num + "_"+ uploadFileName;
    	value.setFilePath(path+uploadFileName);
    	try {
			sv.insert(value);
			if(addFile(upload,path,uploadFileName)){
				this.setSuccess(true);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.setSuccess(false);
		}
    	
    	return SUCCESS;
    }
    public String deleteByIds(){
    	if(CommonUtil.isNotBlank(fileIds)){
    		String ids[] = fileIds.split(",");
    		for(int i = 0;i< ids.length;i++){
    			Map<String,Object> map = new HashMap<String, Object>();
    			map.put("fileId", ids[i]);
    			try {
    				this.deleteFile(ids[i]);
					sv.deleteFile(map);
					this.setSuccess(true);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					this.setSuccess(false);
				}
    		}
    	}
    	return SUCCESS;
    }
    
    private Boolean deleteFile(String fileId){
    	String filePathStr = null;
    	Map<String,Object> map = new HashMap<String, Object>();
    	try {
			resultList = sv.getFileList(map, 0, 0);
			List<HomeWorkFilePojo> list = resultList.getList();
			if(list.size() > 0){
				filePathStr = list.get(0).getFilePath();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	if(CommonUtil.isNotBlank(filePathStr)){
    		//根据路径删除文件
    		File file = new File(filePathStr);
    		if(file.exists()){
    			file.delete();
    		}
    	}
    	return true;
    }
    
    private Boolean addFile(File file,String filePath,String name){
    	if (file != null) {
        	File pathFile = new File(filePath);
    		if(!pathFile.isDirectory()){
    			pathFile.mkdir();
    		}
        	try { 
        		BufferedInputStream bis = new BufferedInputStream( 
                    new FileInputStream(file)); 
        		BufferedOutputStream bos = null; 
                bos = new BufferedOutputStream(new FileOutputStream(filePath + name));
                byte[] buff = new byte[8192]; 
                for (int len = -1; (len = bis.read(buff)) != -1;) { 
                    bos.write(buff, 0, len); 
                } 
                bos.flush(); 
                bis.close(); 
                bos.close();
            } catch (Exception e) { 
                e.printStackTrace(); 
                return false;              
            }
                                                                 
        }else{
        	return false;
        } 
        
    	return true;
    }
    
	public String getFileIds() {
		return fileIds;
	}
	public void setFileIds(String fileIds) {
		this.fileIds = fileIds;
	}
	public Boolean getSuccess() {
		return success;
	}
	public void setSuccess(Boolean success) {
		this.success = success;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public IHomeWorkFileSV getSv() {
		return sv;
	}
	public void setSv(IHomeWorkFileSV sv) {
		this.sv = sv;
	}
	public PageInfo<HomeWorkFilePojo> getResultList() {
		return resultList;
	}
	public void setResultList(PageInfo<HomeWorkFilePojo> resultList) {
		this.resultList = resultList;
	}
	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	public String getLimit() {
		return limit;
	}
	public void setLimit(String limit) {
		this.limit = limit;
	}
	public String getQuery() {
		return query;
	}
	public void setQuery(String query) {
		this.query = query;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getFileID() {
		return fileID;
	}
	public void setFileID(String fileID) {
		this.fileID = fileID;
	}

	/*public void setDownloadFile(InputStream downloadFile) {
		this.downloadFile = downloadFile;
	}
	*/
    
}
